package com.sjy.ylxt.controller;

import cn.dev33.satoken.annotation.SaCheckRole;
import cn.dev33.satoken.annotation.SaMode;
import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONException;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sjy.ylxt.entity.basic.ResultBody;
import com.sjy.ylxt.entity.domain.YlxtAdmin;
import com.sjy.ylxt.entity.domain.YlxtEscorts;
import com.sjy.ylxt.entity.domain.YlxtPatient;
import com.sjy.ylxt.enums.DeleteFlagEnum;
import com.sjy.ylxt.enums.UserRoleEnum;
import com.sjy.ylxt.mapper.YlxtAdminMapper;
import com.sjy.ylxt.mapper.YlxtEscortsMapper;
import com.sjy.ylxt.mapper.YlxtPatientMapper;
import com.sjy.ylxt.service.YlxtAdminService;
import com.sjy.ylxt.service.YlxtEscortsService;
import com.sjy.ylxt.service.YlxtPatientService;
import com.sjy.ylxt.utils.MD5Util;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author: lils
 * @CreateTime: 2024-12-12
 * @Description: 权限登录控制层
 */
/**
 * 权限控制
 */
@RestController
@RequestMapping("/auth")
@Slf4j
public class AuthController {

    @Resource
    private YlxtAdminService adminService;

    @Resource
    private YlxtEscortsService escortsService;

    @Resource
    private YlxtPatientService patientService;

    @Resource
    private YlxtAdminMapper adminMapper;

    @Resource
    private YlxtEscortsMapper escortsMapper;

    @Resource
    private YlxtPatientMapper patientMapper;
    @GetMapping("/current")
    public ResultBody<?> getCurrentUser() {
        String userInfo = StpUtil.getLoginDevice();
        log.info("原始用户信息: {}", userInfo);

        // 使用正则表达式或其他方法准确地转换键值对
        Map<String, String> userMap = Arrays.stream(userInfo.replace("{", "").replace("}", "").split(", "))
                .map(entry -> entry.split("="))
                .collect(Collectors.toMap(entry -> entry[0].trim(), entry -> entry[1].trim()));

        try {
            JSONObject dataObject = new JSONObject(userMap);
            return ResultBody.success(dataObject);
        } catch (JSONException e) {
            log.error("JSON 解析错误: {}", e.getMessage());
            return ResultBody.error("无法解析用户信息");
        }
    }



    /**
     * 用户登录接口
     * @return
     */
    @PostMapping("/login")
    public ResultBody authLogin(@RequestParam String username, @RequestParam String password, @RequestParam String role) {
        try {
            log.info("==> 开始登录");
            Map<String, String> userInfo = new HashMap<>();
            if (role.equals(UserRoleEnum.ADMIN.getCode())) {
                // 查询管理员表
                LambdaQueryWrapper<YlxtAdmin> qw = new LambdaQueryWrapper<>();
                qw.eq(YlxtAdmin::getAdminName, username);
                qw.eq(YlxtAdmin::getPassWord, password);
                YlxtAdmin ylxtAdmin = adminMapper.selectOne(qw);
                if (!ObjectUtil.isEmpty(ylxtAdmin)) {
                    userInfo.put("id", String.valueOf(ylxtAdmin.getId()));
                    userInfo.put("username", ylxtAdmin.getAdminName());
                    userInfo.put("role", role);
                    StpUtil.login(userInfo.get("id"), String.valueOf(userInfo));
                    return ResultBody.success(userInfo);
                } else {
                    return ResultBody.error("权限不足，请切换角色重新登录");
                }
            } else if (role.equals(UserRoleEnum.ESCORTS.getCode())) {
                // 查询陪诊员表
                LambdaQueryWrapper<YlxtEscorts> qw = new LambdaQueryWrapper<>();
                qw.eq(YlxtEscorts::getUserName, username);
                qw.eq(YlxtEscorts::getPassWord, password);
                YlxtEscorts ylxtEscort = escortsMapper.selectOne(qw);
                if (!ObjectUtil.isEmpty(ylxtEscort)) {
                    userInfo.put("id", String.valueOf(ylxtEscort.getId()));
                    userInfo.put("username", ylxtEscort.getUserName());
                    userInfo.put("role", role);
                    StpUtil.login(userInfo.get("id"), String.valueOf(userInfo));
                    return ResultBody.success(userInfo);
                } else {
                    return ResultBody.error("权限不足，请切换角色重新登录");
                }
            } else if (role.equals(UserRoleEnum.PATIENT.getCode())) {
                // 查询患者表
                LambdaQueryWrapper<YlxtPatient> qw = new LambdaQueryWrapper<>();
                qw.eq(YlxtPatient::getUserName, username);
                qw.eq(YlxtPatient::getPassword, password);
                YlxtPatient ylxtPatient = patientMapper.selectOne(qw);
                if (!ObjectUtil.isEmpty(ylxtPatient)) {
                    userInfo.put("id", String.valueOf(ylxtPatient.getId()));
                    userInfo.put("username", ylxtPatient.getUserName());
                    userInfo.put("role", role);
                    StpUtil.login(userInfo.get("id"), String.valueOf(userInfo));
                    return ResultBody.success(userInfo);
                } else {
                    return ResultBody.error("权限不足，请切换角色重新登录");
                }
            } else {
                return ResultBody.error("权限不足，请切换角色重新登录");
            }
        } catch (Exception e) {
            log.error("==> 登录失败，报错信息为{}", e.getMessage());
            return  ResultBody.error("账号密码错误");
        }
    }


    /**
     * 退出登录接口
     * @return
     */
    @PostMapping("/logout")
    public ResultBody authLogout(){
        StpUtil.logout();
        return ResultBody.success("退出登录成功");
    }

    /**
     * 索引页添加
     */
    @PostMapping("/index")
    public ResultBody<?> index() {
        Map<String,String> version = new HashMap<>();
        version.put("version","3.2.0");
        return ResultBody.success(version);
    }

//    /**
//     * 陪诊员注册
//     */
//    @PostMapping("/register")
//    public SaResult escortsRegister(@RequestBody AddEscortsDTO dto) {
//        try {
//            log.info("==> 开始陪诊员注册");
//            YlxtEscorts escorts = O2O.escortsToDomain(dto);
//            escorts.setPassword(MD5Util.encryptToMD5(escorts.getPassword()));
//            escortsService.save(escorts);
//            log.info("==> 陪诊员注册成功");
//            return SaResult.ok("注册成功");
//        } catch (Exception e) {
//            log.error("==> 陪诊员注册失败，报错信息为{}",e.getMessage());
//            return SaResult.error("注册失败");
//        }
//    }
//
//    /**
//     * 患者注册
//     */
//    @PostMapping("/patient-register")
//    public SaResult patientRegister(@RequestBody AddPatientDTO dto) {
//        try {
//            log.info("==> 开始患者注册");
//            YlxtPatient ylxtPatient = O2O.patientToDomain(dto);
//            ylxtPatient.setPassword(MD5Util.encryptToMD5(ylxtPatient.getPassword()));
//            patientService.save(ylxtPatient);
//            log.info("==> 患者注册成功");
//            return SaResult.ok("注册成功");
//        } catch (Exception e) {
//            log.error("==> 患者注册失败，报错信息为{}",e.getMessage());
//            return SaResult.error("注册失败");
//        }
//    }
    /**
     * 用户注册接口
     */
    @PostMapping("/register")
    public ResultBody register(
            @RequestParam String userName,
            @RequestParam String password,
            @RequestParam String email,
            @RequestParam String phoneNumber,
            @RequestParam String role,
            @RequestParam(required = false) String companionCertificate,
            @RequestParam(required = false) String companionExperience) {
        try {
            log.info("==> 开始用户注册");
            if (role.equals(UserRoleEnum.ADMIN.getCode())) {
                // 管理员注册逻辑
                // AdminDTO adminDTO = new AdminDTO();
                // adminDTO.setUserName(userName);
                // adminDTO.setPassword(MD5Util.encryptToMD5(password));
                // adminDTO.setEmail(email);
                // adminDTO.setPhoneNumber(phoneNumber);
                // adminService.save(adminDTO);
                return ResultBody.error("管理员注册暂未实现");
            } else if (role.equals(UserRoleEnum.ESCORTS.getCode())) {
                YlxtEscorts escorts = new YlxtEscorts();
                escorts.setUserName(userName);
                escorts.setPassWord(password);
                escorts.setEmail(email);
                escorts.setPhoneNumber(phoneNumber);
                escorts.setCompanionCertificate(companionCertificate);
                escorts.setCompanionExperience(companionExperience);
                escorts.setDeleteFlag(DeleteFlagEnum.UN_DELETE_FLAG.getCode());
                escortsService.save(escorts);
                log.info("==> 陪诊员注册成功");
                return ResultBody.success("注册成功");
            } else if (role.equals(UserRoleEnum.PATIENT.getCode())) {
                YlxtPatient ylxtPatient = new YlxtPatient();
                ylxtPatient.setUserName(userName);
                ylxtPatient.setPassword(password);
                ylxtPatient.setEmail(email);
                ylxtPatient.setPhoneNumber(phoneNumber);
                ylxtPatient.setDeleteFlag(DeleteFlagEnum.UN_DELETE_FLAG.getCode());
                patientService.save(ylxtPatient);
                log.info("==> 患者注册成功");
                return ResultBody.success("注册成功");
            } else {
                return ResultBody.error("无效的角色");
            }
        } catch (Exception e) {
            log.error("==> 用户注册失败，报错信息为{}", e.getMessage());
            return ResultBody.error("注册失败");
        }
    }

    /**
     * 修改密码
     */
    @PostMapping("/edit-password")
    public ResultBody<?> editPassword(@RequestParam String oldPassword, @RequestParam String newPassword, @RequestParam String role,
                                 @RequestParam String name) {
        try {
            if (role.equals(UserRoleEnum.ADMIN.getCode())) {
                YlxtAdmin admin = adminMapper.selectOne(new QueryWrapper<YlxtAdmin>().eq("user_name", name));
                    admin.setPassWord(newPassword);
                    adminMapper.updateById(admin);
                    log.info("==> 修改管理员密码成功");
                    return ResultBody.success("修改密码成功");
            } else if (role.equals(UserRoleEnum.PATIENT.getCode())) {
                YlxtPatient patient = patientMapper.selectOne(new QueryWrapper<YlxtPatient>().eq("user_name", name));
                    patient.setPassword(newPassword);
                    patientMapper.updateById(patient);
                    log.info("==> 修改患者密码成功");
                    return ResultBody.success("修改密码成功");
            } else if (role.equals(UserRoleEnum.ESCORTS.getCode())) {
                YlxtEscorts escorts = escortsMapper.selectOne(new QueryWrapper<YlxtEscorts>().eq("user_name", name));
                    escorts.setPassWord(newPassword);
                    escortsMapper.updateById(escorts);
                    log.info("==> 修改陪诊员密码成功");
                    return ResultBody.success("修改密码成功");
            } else{
                return ResultBody.error("无效的角色");
            }
        }catch (Exception e){
            log.error("==> 修改密码失败，报错信息为{}",e.getMessage());
            return ResultBody.error("修改密码失败");
        }
    }
}
